package com.qd.panda.gas.discount.autohome;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.util.SpringContextHolder;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.event.AutoHomeEvent;
import com.qd.common.sys.domain.entity.log.SendLogDTO;
import com.qd.common.sys.event.SendLogEvent;
import com.qd.panda.gas.discount.autohome.req.OrderDTO;
import com.qd.panda.service.stroke.order.UserStrokeOrderPreferentialLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpMethod;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 加油信息处理
 *
 * @author sjk
 * @create 2022-10-12 10:02
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AutoHomeSyncService {
    private final UserStrokeOrderPreferentialLogService userStrokeOrderPreferentialLogService;
    private final AutoHomeHttpServiceImpl autoHomeHttpService;
    @Async
    @EventListener(classes = AutoHomeEvent.class)
    @Transactional(rollbackFor = Exception.class)
    public void doNotify(AutoHomeEvent autoHomeEvent) {
        long start = System.currentTimeMillis();
        String orderId = (String) autoHomeEvent.getSource();
        log.info("支付成功，回调汽车之家接口,orderId： {}", orderId);
        SendLogDTO sendLog = new SendLogDTO();
        sendLog.setBid(orderId)
                .setSendState(ConstantDto.SF1)
                .setAddTime(LocalDateTime.now())
                .setLogType(PandaConstant.LOG_TYPE_AUTO_HOME_PAY_NOTIFY)
                .setReqMethod(HttpMethod.POST.name());
        try {
            try {
                //查询壳牌的订单号
                final String thirdPartyOrderId = userStrokeOrderPreferentialLogService.getBaseMapper().getThirdPartyOrderId(orderId, PandaConstant.PLATFORM_EXTEND_SHELL);
                log.info("壳牌订单号: {}", thirdPartyOrderId);
                if (StringUtils.hasLength(thirdPartyOrderId)) {
                    OrderDTO orderDTO = new OrderDTO();
                    orderDTO.setOrderNo(thirdPartyOrderId);
                    orderDTO.setSendLogDTO(sendLog);
                    autoHomeHttpService.order(orderDTO);
                    orderDTO.freeData();
                }
            } catch (Exception e) {
                final String message = ExceptionUtil.getMessage(e);
                sendLog.setErrMsg(message);
                sendLog.setSendState(ConstantDto.SF0);
            }
        } finally {
            long end = System.currentTimeMillis();
            sendLog.setTimeConsumer(end-start);
            SpringContextHolder.publishEvent(new SendLogEvent(sendLog));
        }
    }
}